package de.sendorian.app.forumArchive;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.finder.Finder;
import de.sendorian.app.forumArchive.repository.ForumRepository;


/**
 * This class updates a forum, if necessary.
 * 
 * @author sendorian
 * 
 */
@Service
public class ForumUpdater implements Runnable {

    private static final Logger LOG = Logger.getLogger(ForumUpdater.class);

    private ForumRepository forumRepository;
    private Finder<String, Forum> forumFinder;
    private TopicUpdater topicUpdater;
    private String baseUrl;

    
    public void run() {
        updateAllForums();
        
        forumRepository.shutdownDatabase();
        LOG.info("Finished!");
    }
    

    /**
     * Updated all forums, the default ForumFinder finds, if necessary and
     * persists all changes.
     * 
     * @return the found forums, updated with all changes.
     */
    public List<Forum> updateAllForums() {
        List<Forum> forums = forumFinder.find(baseUrl);
        List<Forum> persistedForums = new ArrayList<Forum>(forums.size());

        for (Forum forum : forums) {
            Forum persistentForum = forumRepository.findByName(forum.getName());
            if (persistentForum != null) {
                forum = persistentForum;
            }

            LOG.info("Finding topics for forum \"" + forum.getName() + "\"");
            topicUpdater.updateTopicsInForum(forum);
            persistedForums.add(forum);
        }
        return persistedForums;
    }


    @Autowired
    public void setForumRepository(ForumRepository forumRepository) {
        this.forumRepository = forumRepository;
    }


    @Value("#{config.forumFinder}")
    public void setForumFinder(Finder<String, Forum> forumFinder) {
        this.forumFinder = forumFinder;
    }


    @Autowired
    public void setTopicUpdater(TopicUpdater topicUpdater) {
        this.topicUpdater = topicUpdater;
    }


    @Value("#{config.baseUrl}")
    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }
}
